from django.conf import settings
from fdfs_client.client import Fdfs_client
from rest_framework.response import Response
from rest_framework.viewsets import ModelViewSet
from meiduo_mall_admin.my_paginate import MyPageNumberPagination
from goods.models import Brand
from . import brand_serializers


class BrandViews(ModelViewSet):
    pagination_class = MyPageNumberPagination
    serializer_class = brand_serializers.BrandSerializer
    queryset = Brand.objects.all()

    def create(self, request, *args, **kwargs):
        # 获取新增品牌logo
        log_image = self.request.FILES.get("logo")
        logo_name = request.data.get("name")
        logo_first_letter = request.data.get("first_letter")

        # 判断logo
        if not all([log_image, logo_name, logo_first_letter]):
            return Response(status=400)

        # logo 上传入库
        client = Fdfs_client(settings.FDFS_CONFIG)
        ret = client.upload_by_buffer(log_image.read())

        if ret["Status"] != 'Upload successed.':
            return Response(status=400)

        logo_url = ret.get('Remote file_id')
        Brand.objects.create(logo=logo_url, name=logo_name, first_letter=logo_first_letter)
        return Response(status=201)

    def update(self, request, *args, **kwargs):
        # 获取新增品牌logo
        new_log_image = self.request.FILES.get("logo")
        new_logo_name = request.data.get("name")
        new_logo_first_letter = request.data.get("first_letter")
        pk = self.kwargs.get("pk")

        # 判断logo
        if not all([new_log_image, new_logo_name, new_logo_first_letter]):
            return Response(status=400)

        # logo 上传入库
        client = Fdfs_client(settings.FDFS_CONFIG)
        ret = client.upload_by_buffer(new_log_image.read())

        if ret["Status"] != 'Upload successed.':
            return Response(status=400)

        new_logo_url = ret.get('Remote file_id')
        Brand.objects.filter(pk=pk).update(logo=new_logo_url, name=new_logo_name, first_letter=new_logo_first_letter)
        return Response(status=200)


